import time
from calendar import month_name

from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import get_object_or_404, render_to_response
from django.contrib.auth.decorators import login_required
from django.core.context_processors import csrf
from django.core.paginator import Paginator, InvalidPage, EmptyPage
from django.core.urlresolvers import reverse

from models import *
from django.forms import ModelForm

class BlogCommentForm(ModelForm):
    class Meta:
        model = BlogComment
        exclude = ["post"]
    def __init__(self, *args, **kwargs):
        super(BlogCommentForm, self).__init__(*args, **kwargs) # Call to ModelForm constructor
        self.fields['body'].widget.attrs['cols'] = 60
        self.fields['body'].widget.attrs['rows'] = 15

def hello(request):
    return HttpResponse("Hello world")

def v_home(request):
    return render_to_response('home.html', {'brief_intro' : 'Overview of myself.'})

def v_arts(request):
    posts = ArtPost.objects.all().order_by("-created")
    return render_to_response('arts.html', dict(brief_intro='Artwork collection.', posts = posts))

def v_game_designs_list(request):
    posts = GameDesignPost.objects.all().order_by("-created")
    return render_to_response('game_designs_list.html', dict(brief_intro='Game design ideas.', posts = posts))

def v_projects_list(request):
    posts = ProjectPost.objects.all().order_by("-created")
    return render_to_response('projects.html', dict(brief_intro='Projects collection.', posts = posts))


def v_blog_list(request):
    """Main listing."""
    posts = BlogPost.objects.all().order_by("-created")
    paginator = Paginator(posts, 10)
    try: page = int(request.GET.get("page", '1'))
    except ValueError: page = 1
    
    categories = BlogCategory.objects.all()

    try:
        posts = paginator.page(page)
    except (InvalidPage, EmptyPage):
        posts = paginator.page(paginator.num_pages)

    return render_to_response("blog/blog_list.html", dict(categories=categories, posts=posts, user=request.user,
                                                post_list=posts.object_list, months=v_blog_mkmonth_lst(), brief_intro='Xcheng\'s Blog.'))


def v_projects_post(request, pk):
    post = ProjectPost.objects.get(pk=pk)
    d = dict(post=post, brief_intro='Xcheng\'s Projects.')
    print post
    d.update(csrf(request))
    return render_to_response("project_post.html", d)


def v_game_designs_post(request, pk):
    post = GameDesignPost.objects.get(pk=pk)
    d = dict(post=post, brief_intro='Game design ideas.')
    print post
    d.update(csrf(request))
    return render_to_response("game_designs_post.html", d)

def v_blog_post(request, pk):
    """Single post with comments and a comment form."""
    post = BlogPost.objects.get(pk=pk)
    comments = BlogComment.objects.filter(post=post)
    d = dict(post=post, comments=comments, form=BlogCommentForm(), user=request.user, brief_intro='Xcheng\'s Blog.')
    d.update(csrf(request))
    return render_to_response("blog/blog_post.html", d)

def v_blog_delete_comment(request, post_pk, pk=None):
    """Delete comment(s) with primary key `pk` or with pks in POST."""
    if request.user.is_staff:
        if not pk: pklst = request.POST.getlist("delete")
        else: pklst = [pk]

        for pk in pklst:
            BlogComment.objects.get(pk=pk).delete()
        return HttpResponseRedirect(reverse("xcheng.views.v_blog_post", args=[post_pk]))

def v_blog_add_comment(request, pk):
    """Add a new comment."""
    p = request.POST

    if p.has_key("body") and p["body"]:
        author = "Anonymous"
        if p["author"]: author = p["author"]
        comment = BlogComment(post=BlogPost.objects.get(pk=pk))

        # save comment form
        cf = BlogCommentForm(p, instance=comment)
        cf.fields["author"].required = False
        comment = cf.save(commit=False)

        # save comment instance
        comment.author = author
        notify = True
        if request.user.username == "ak": notify = False
        comment.save(notify=notify)
    return HttpResponseRedirect(reverse("xcheng.views.v_blog_post", args=[pk]))

def v_blog_mkmonth_lst():
    """Make a list of months to show archive links."""
    if not BlogPost.objects.count(): return []

    # set up vars
    year, month = time.localtime()[:2]
    first = BlogPost.objects.order_by("created")[0]
    fyear = first.created.year
    fmonth = first.created.month
    months = []

    # loop over years and months
    for y in range(year, fyear-1, -1):
        start, end = 12, 0
        if y == year: start = month
        if y == fyear: end = fmonth-1

        for m in range(start, end, -1):
            months.append((y, m, month_name[m]))
    return months

def v_blog_month(request, year, month):
    """Monthly archive."""
    categories = BlogCategory.objects.all()
    posts = BlogPost.objects.filter(created__year=year, created__month=month)
    return render_to_response("blog/blog_list.html", dict(categories=categories, post_list=posts, user=request.user,
                                                months=v_blog_mkmonth_lst(), archive=True, brief_intro='Xcheng\'s Blog.'))

def v_blog_category(request, cate):
    """Category."""
    categories = BlogCategory.objects.all()
    posts = BlogPost.objects.filter(category__id=cate)
    return render_to_response("blog/blog_list.html", dict(categories=categories, post_list=posts, user=request.user,
                                                months=v_blog_mkmonth_lst(), archive=True, brief_intro='Xcheng\'s Blog.'))